package com.boc.langxiang.ui.dialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.boc.langxiang.R;
import com.boc.langxiang.alipay.PayResult;
import com.boc.langxiang.contract.shop.PayContract;
import com.boc.langxiang.entity.bean.AliPayOrderInfo;
import com.boc.langxiang.entity.bean.OrderInfo;
import com.boc.langxiang.entity.request.PayRequest;
import com.boc.langxiang.presenter.shop.PayPresenter;
import com.boc.langxiang.util.T;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Li Guoxi on 2016/7/4.
 */
public class OrderPayDialog extends Dialog implements View.OnClickListener, PayContract.View {
    @BindView(R.id.close_layout)
    RelativeLayout closeLayout;
    @BindView(R.id.order_id_tv)
    TextView orderIdTv;
    @BindView(R.id.price_tv)
    TextView priceTv;
    @BindView(R.id.alipay_checkmark_iv)
    ImageView alipayCheckmarkIv;
    @BindView(R.id.alipay_layout)
    RelativeLayout alipayLayout;
    @BindView(R.id.wechat_checkmark_iv)
    ImageView wechatCheckmarkIv;
    @BindView(R.id.wechat_layout)
    RelativeLayout wechatLayout;
    @BindView(R.id.confirm_btn)
    Button confirmBtn;
    private Context mContext;
    private LayoutInflater inflater;

    private final int _Pay_AliPay = 1001;
    private final int _Pay_Wechat = 1002;

    private OnPayCancelOrSuccess mOnPayCancelOrSuccess;

    private int mPayWay;

    private PayPresenter payPresenter;

    private OrderInfo mOrderinfo;

    private final int[] payWays = {_Pay_AliPay, _Pay_Wechat};

    private WaitingDialog mWaitingDialog;
    private long mExitTime;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1000:
                    if (mWaitingDialog != null) {
                        mWaitingDialog.dismissAllowingStateLoss();
                    }
            }
        }
    };

    public OrderPayDialog(Context context) {
        super(context);
        this.mContext = context;
        this.inflater = LayoutInflater.from(context);
    }

    public OrderPayDialog(Context context, OrderInfo orderInfo) {
        super(context);
        this.mOrderinfo = orderInfo;
        this.mContext = context;
        this.inflater = LayoutInflater.from(context);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        payPresenter = new PayPresenter(this);
        Window window = getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.requestFeature(Window.FEATURE_NO_TITLE);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.setWindowAnimations(R.style.BottomDialogAnimation);


        View view = inflater.inflate(R.layout.dialog_order_pay, null);
        ButterKnife.bind(this, view);
        setContentView(view);
        setCancelable(false);
        initViews();
    }

    private void initViews() {
        if (mOrderinfo != null) {
            orderIdTv.setText(mOrderinfo.getOrderid());
            priceTv.setText(mOrderinfo.getPrice());
        }
        closeLayout.setOnClickListener(this);
        alipayLayout.setOnClickListener(this);
        wechatLayout.setOnClickListener(this);
        confirmBtn.setOnClickListener(this);
        setPayWay(0);
    }

    private void setPayWay(int index) {
        alipayCheckmarkIv.setVisibility(View.GONE);
        wechatCheckmarkIv.setVisibility(View.GONE);
        mPayWay = payWays[index];
        switch (mPayWay) {
            case _Pay_AliPay:
                alipayCheckmarkIv.setVisibility(View.VISIBLE);
                break;
            case _Pay_Wechat:
                wechatCheckmarkIv.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_layout:
                new AlertDialog.Builder(mContext)
                        .setMessage("您尚未支付，是否取消支付？")
                        .setNegativeButton("否", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .setPositiveButton("稍后支付", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dismiss();
                                if (mOnPayCancelOrSuccess != null) {
                                    mOnPayCancelOrSuccess.onCancel();
                                }
                                dialog.dismiss();
                            }
                        })
                        .create()
                        .show();
                break;

            case R.id.alipay_layout:
                setPayWay(0);
                break;

            case R.id.wechat_layout:
                Toast.makeText(mContext, "微信支付暂未开通!", Toast.LENGTH_SHORT).show();
//                setPayWay(1);
                break;

            case R.id.confirm_btn:
                switch (mPayWay) {
                    case _Pay_AliPay:
                        onAliPay();
                        dismiss();
                        break;
                    case _Pay_Wechat:
                        onWechatPay();
                        dismiss();
                        break;
                }
                break;

        }
    }

    private void onWechatPay() {
        //        mPayPresenter.pay(mOrderId, PayRequest.PAY_WAY_WECHATPAY);
    }

    private void onAliPay() {
        payPresenter.pay(mOrderinfo.getOrderid(), PayRequest.PAY_WAY_ALIPAY);
    }

    private Handler mAliPayHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case _Pay_AliPay:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String resultInfo = payResult.getResult();
                    Log.e("ALI_PAY_RESULT_INFO", resultInfo);
                    String resultStatus = payResult.getResultStatus();
                    if (TextUtils.equals(resultStatus, "9000")) {
                        T.showShort(mContext, "支付成功");
                        if (mOnPayCancelOrSuccess != null) {
                            mOnPayCancelOrSuccess.onSuccess();
                        }
                    } else {
                        Toast.makeText(mContext, "支付失败", Toast.LENGTH_SHORT).show();
                        if (mOnPayCancelOrSuccess != null) {
                            mOnPayCancelOrSuccess.onCancel();
                        }
                    }
                    dismiss();
                    break;
            }
            return false;
        }
    });

    @Override
    public void onGetPayInfoSuccess(final AliPayOrderInfo aliPayOrderInfo) {
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask payTask = new PayTask((Activity) mContext);
                Map<String, String> result = payTask.payV2(aliPayOrderInfo.getAlipaySign(), true);
                Message message = new Message();
                message.what = _Pay_AliPay;
                message.obj = result;
                mAliPayHandler.sendMessage(message);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    @Override
    public void showLoading() {
        showProgressDialog("正在获取支付信息");
    }

    @Override
    public void hideLoading() {
        dismissDialog();
    }

    @Override
    public void onError(String code, String msg) {
        T.showShort(mContext, msg);
    }

    private void showProgressDialog(String content) {
        showProgressDialog(content, true);
    }

    private void showProgressDialog(String content, boolean cancelable) {
        mExitTime = System.currentTimeMillis();
        mWaitingDialog = new WaitingDialog();
        mWaitingDialog.setContent(content, cancelable);
        mWaitingDialog.show(((FragmentActivity) mContext).getSupportFragmentManager(), getClass().getSimpleName());
    }

    private void dismissDialog() {
        if (mWaitingDialog != null) {
            if ((System.currentTimeMillis() - mExitTime) > 500) {
                mWaitingDialog.dismissAllowingStateLoss();
            } else {
                mHandler.sendEmptyMessageDelayed(1000, 500 + mExitTime - System.currentTimeMillis());
            }
        }
    }

    public void setOnPayCancelOrSuccess(OnPayCancelOrSuccess onPayCancelOrSuccess) {
        this.mOnPayCancelOrSuccess = onPayCancelOrSuccess;
    }
}
